package com.dome.serice.impl;

import com.dome.common.utils.DateUtlis;
import com.dome.common.utils.RedisUtils;
import com.dome.common.constant.BaseConstant;
import com.dome.pojo.redis.vo.TokenVo;
import com.dome.serice.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.UUID;

/**
 * 描述：
 *
 * @author tangshunkai
 * @Date 2022/4/26 16:39
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public TokenVo createToken(String userId) {
        String check = (String)redisUtils.get(userId);
        TokenVo tokenVo = new TokenVo();
        String token = UUID.randomUUID().toString();
        String dateTime = DateUtlis.getDateTime();
        tokenVo.setUserId(userId);
        tokenVo.setToken(token);
        tokenVo.setExpireTime(BaseConstant.TOKEN_EXPIRE_TIME);
        tokenVo.setCreateTime(dateTime);
        tokenVo.setUpdateTime(dateTime);
        // 设置token过期时间30 分钟
        if(Objects.nonNull(check)){
            redisUtils.del(check);
        }
        redisUtils.set(userId,token);
        redisUtils.set(token,tokenVo, BaseConstant.TOKEN_EXPIRE_TIME);
        return tokenVo;
    }

    @Override
    public boolean updateToken(String token) {
        return redisUtils.setExpire(token,BaseConstant.TOKEN_EXPIRE_TIME);
    }

    @Override
    public boolean deleteToken(String token) {
        try {
            redisUtils.del(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
